import 'package:alipay_kit/alipay_kit.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';
import 'package:roundcheckbox/roundcheckbox.dart';
import '../../network/Api.dart';
import '../../theme/theme_color.dart';
import '../../utils/loading.dart';
import '../../utils/provider.dart';
// import 'package:tobias/tobias.dart' ;

class MeStatusUI extends StatelessWidget {
  const MeStatusUI({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _MeStatusUIWidget();
  }
}

class _MeStatusUIWidget extends StatefulWidget {
  const _MeStatusUIWidget({Key? key}) : super(key: key);

  @override
  State<_MeStatusUIWidget> createState() => _MeStatusUIWidgetState();
}

class _MeStatusUIWidgetState extends State<_MeStatusUIWidget> {
  final List _listData = [];
  bool check = false;
  int _index = 0;
  late String _ID = '';
  late String singleState = '';

  getCheckBoxBorderColor() {
    if (check) {
      return const Color(0xFF7F69D9);
    } else {
      return const Color(0xFFD1D1D1);
    }
  }

  final ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;
    return AppWidget.navTitleBar(
      bgColor: Colors.white,
      title: "个人状态",
      childWidget: Column(
        children: [
          SizedBox(
            height: 110,
            child: ListView.builder(
              controller: _scrollController,
              itemBuilder: (_, index) {
                bool isSelected = index == _index;
                return _buildItems(
                    _listData[index], index, isSelected, screenWidth);
              },
              itemCount: _listData.length,
            ),
          ),
          const SizedBox(
            height: 10,
          ),
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 14),
            child: Text.rich(
              TextSpan(
                style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold),
                children: [
                  WidgetSpan(
                    child: Image.asset(
                      'images/ic_personTip.png',
                      width: 13,
                      height: 13,
                    ),
                  ),
                  const TextSpan(
                    text: ' 提示：非单身状态在个人头像展示非单身不征婚标识，不能打开遇见并且不能参与相亲',
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(
            height: 30,
          ),
          Column(
            children: [
              const Text('图例'),
              const SizedBox(
                height: 8,
              ),
              Image.asset(
                "images/ic_fdsbzh_tuli.png",
                width: 140,
                height: 140,
              ),
            ],
          )
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();

    _getMemberstateList();
  }

  _getMemberstateList() async {
    final res = await Api.getInstance().memberstateList();
    final data = res['data']['states'];

    if (data != null) {
      List list = data;
      if (list.isNotEmpty) {
        _listData.clear();
        setState(() {
          // _index = res['data']['currState'] == 0 ? 0 : 1;

          _index = res['data']['currState'];

          _listData.addAll(list);
        });
      }
    }
  }

  // member/state/list
  @override
  _buildItems(Map map, int index, bool isSelected, double screenWidth) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _index = index;
        });
        _ID = map["id"];
        if (_index == 0) {
          _chooseNetWork(context, _ID, '确认选择单身状态');
        } else {
          _chooseNetWork(context, _ID, '确认选择非单身状态');
        }
      },
      child: Container(
        color: isSelected
            ? const Color.fromRGBO(127, 105, 217, 0.14)
            : const Color.fromRGBO(246, 248, 250, 1),

        // padding: const EdgeInsets.only(left: 14,right: 14,top: 10),
        margin: const EdgeInsets.fromLTRB(14, 10, 14, 0),
        padding: const EdgeInsets.symmetric(horizontal: 10),
        height: 45,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              map["singleState"] == 0 ? '单身' : '非单身',
              style: TextStyle(
                color: ThemeColor.textColor,
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
            Image.asset(
              isSelected
                  ? 'images/ic_myStatusSec.png'
                  : 'images/ic_myStatusNoSec.png',
              width: 13,
              height: 13,
            ),

            // RoundCheckBox(
            //     size: 16, //checkBox大小
            //     checkedWidget: const Icon(
            //       Icons.check,
            //       color: Colors.white,
            //       size: 8,
            //     ),
            //     checkedColor: const Color(0xFF7F69D9),
            //     uncheckedColor: const Color(0xFFF6F8FA),
            //     border: Border.all(color: getCheckBoxBorderColor(), width: 1),
            //
            //     isChecked: isSelected,
            //     onTap: (selected) {
            //       _index = index;
            //     //   _ID = map["id"];
            //     //   // _singleState = int map['singleState'];
            //     //   if(_index == 0 ) {
            //     //     _chooseNetWork(context, _ID, '确认选择单身状态');
            //     //   } else {
            //     //     _chooseNetWork(context, _ID, '确认选择非单身状态');
            //     //     // _getweixinPay(_ID);
            //     //   }
            //     }
            //
            //     ),
          ],
        ),
      ),
    );
  }
}

Future<void> _chooseNetWork(context, String ID, String title) async {
  showCupertinoDialog(
      context: context,
      builder: (context) {
        return CupertinoAlertDialog(
          title: Text(title),
          actions: <Widget>[
            CupertinoDialogAction(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text(
                '取消',
                style: TextStyle(fontSize: 16, color: Colors.black),
              ),
            ),
            CupertinoDialogAction(
              onPressed: () {
                Navigator.pop(context);
                if (title == '确认选择单身状态') {
                  _chooseNetWork1(context, ID, '提示：重返单身状态需支付9.9元');
                } else {
                  print('vvvvvvv');
                  Navigator.pop(context, true);
                  if (kIsWeb) {
                    _getweixinPay(ID);
                  } else {
                    _toAliPay(ID);
                  }
                }
                // _toAliPay(ID);
              },
              child: Text(
                '确定',
                style: TextStyle(fontSize: 16, color: ThemeColor.appColor),
              ),
            ),
          ],
        );
      });
}

Future<void> _chooseNetWork1(context, String ID, String title) async {
  showCupertinoDialog(
      context: context,
      builder: (context) {
        return CupertinoAlertDialog(
          title: Text(title),
          actions: <Widget>[
            CupertinoDialogAction(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text(
                '取消',
                style: TextStyle(fontSize: 16, color: Colors.black),
              ),
            ),
            CupertinoDialogAction(
              onPressed: () {
                Navigator.pop(context, true);
                if (kIsWeb) {
                  _getweixinPay(ID);
                } else {
                  _toAliPay(ID);
                }
              },
              child: Text(
                '确定',
                style: TextStyle(fontSize: 16, color: ThemeColor.appColor),
              ),
            ),
          ],
        );
      });
}

// 支付宝支付
void _toAliPay(String id) async {
  final res = await Api.getInstance().zhifubaoPay(id);

  final payInfo = res['data']['data']['payPath'];

  if (res['code'] == 0) {
    AlipayKitPlatform.instance.pay(
      orderInfo: payInfo,
      dynamicLaunch: true,
    );
  } else {
    toast(res['msg']);
  }
}

_getweixinPay(String id) async {
  final res = await Api.getInstance().weixinPay(id);
  final data = res['data'];

  if (res['code'] == 0 &&
      res['data'] != null &&
      res['data']['signature'] != null) {
    final payInfo = res['data']['signature'];
    if (kIsWeb) {
      var js;
      final jsCtx = js.context;
      jsCtx['wePayCallback'] = _wePayCallback;
      jsCtx.callMethod("onBridgeReady", [
        payInfo['appId'],
        payInfo['timestamp'].toString(),
        payInfo['nonce'],
        payInfo['pack'],
        "MD5",
        payInfo['signature']
      ]);
    } else {
      var fluwx;
      fluwx.payWithWeChat(
          appId: payInfo['appId'],
          partnerId: payInfo['partnerId'],
          prepayId: payInfo['prepayId'],
          packageValue: payInfo['pack'],
          nonceStr: payInfo['nonce'],
          timeStamp: payInfo['timestamp'],
          sign: payInfo['signature']);
      fluwx.weChatResponseEventHandler.listen((event) {
        if (event.isSuccessful) {
          _paySuccess();
        } else {
          toast(event.errStr ?? "未知错误");
        }
      });
    }
  } else {
    toast(res['msg']);
  }
}

_wePayCallback(res) {
  if (res == 'ok') {
    _paySuccess();
  } else {
    toast('支付失败');
  }
}

_paySuccess() {
  // toast("支付成功");
  int buyNum = 0;
  // for (var e in _list) {
  //   if (e['id'] == _checkId) {
  //     buyNum = e['goodsNum']??0;
  //     break;
  //   }
  // }
  // Navigator.of(context).pop(buyNum);
}
